document.addEventListener('DOMContentLoaded', async () => {
  // 获取当前标签页
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  // 向content script发送消息获取图片
  chrome.tabs.sendMessage(tab.id, { action: 'getImages' }, (images) => {
    const imageContainer = document.getElementById('imageContainer');
    const imageCount = document.getElementById('imageCount');
    
    if (!images || images.length === 0) {
      imageCount.textContent = '未找到图片';
      return;
    }
    
    imageCount.textContent = `找到 ${images.length} 张图片`;
    
    // 显示所有图片
    images.forEach((img, index) => {
      const div = document.createElement('div');
      div.className = 'image-item';
      
      const imgElement = document.createElement('img');
      imgElement.src = img.url;
      imgElement.alt = img.alt;
      imgElement.title = `${img.width}x${img.height}`;
      
      const downloadBtn = document.createElement('button');
      downloadBtn.className = 'download-btn';
      downloadBtn.textContent = '下载';
      downloadBtn.onclick = () => {
        chrome.downloads.download({
          url: img.url,
          filename: `image_${index + 1}.${getFileExtension(img.url)}`
        });
      };
      
      div.appendChild(imgElement);
      div.appendChild(downloadBtn);
      imageContainer.appendChild(div);
    });
  });
});

// 获取文件扩展名
function getFileExtension(url) {
  const extension = url.split('.').pop().toLowerCase();
  const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
  return validExtensions.includes(extension) ? extension : 'jpg';
} 